/*
 * PACKAGE NAME: com.jodinfo.outmirror.api.loseform.service
 * FILE    NAME: LoseformDaoImpl.java
 * COPYRIGHT: Copyright(c) © 2016 heroj Company Ltd. All Rights Reserved
 */ 
package com.jodinfo.outmirror.api.loseform.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.mengyun.tcctransaction.utils.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.hero.common.web.context.UserContext;
import com.hero.common.web.excel.ExcelImportContext;
import com.hero.common.web.excel.IExcelImportData;
import com.hero.common.web.excel.util.ExcelExport;
import com.hero.core.constant.SysConstant;
import com.hero.core.entity.IPlatformUser;
import com.hero.core.entity.PageResult;
import com.hero.core.entity.ResponseEntity;
import com.hero.core.exception.AbstractGenericException;
import com.hero.core.exception.BusinessException;
import com.hero.core.util.DateUtils;
import com.hero.core.util.StringUtils;
import com.hero.core.util.ValidationUtil;
import com.jodinfo.outmirror.api.dictionary.util.DictionaryUtil;
import com.jodinfo.outmirror.api.loseform.entity.LoseformEntity;
import com.jodinfo.outmirror.api.loseformbarcode.entity.LoseformBarcodeEntity;
import com.jodinfo.outmirror.api.loseformbarcode.service.LoseformBarcodeQueryService;
import com.jodinfo.outmirror.api.purbarcode.entity.PurBarcodeEntity;
import com.jodinfo.outmirror.api.purbarcode.service.PurBarcodeQueryService;
import com.jodinfo.outmirror.api.user.entity.UserEntity;
import com.jodinfo.outmirror.api.user.service.UserQueryService;

@Service(value="loseformBizService")
public class LoseformBizServiceImpl implements LoseformBizService,IExcelImportData{
    private static final Logger logger = LoggerFactory.getLogger(LoseformBizServiceImpl.class);
 	
 	@Resource(name="loseformDmlService")
	private LoseformDmlService LoseformDmlService;
	@Resource(name="loseformQueryService")
	private LoseformQueryService LoseformQueryService;
	@Resource(name="loseformTransactionService")
	private LoseformTransactionService LoseformTransactionService;
	@Resource(name="purBarcodeQueryService")
	private PurBarcodeQueryService purBarcodeQueryService;
	@Resource(name="loseformBarcodeQueryService")
	private LoseformBarcodeQueryService loseformBarcodeQueryService;
	@Resource(name="userQueryService")
	private UserQueryService userQueryService;
	
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformBizService#addLoseform(LoseformEntity LoseformEntity)
	 * @param LoseformEntity LoseformEntity
	 * @return int
	 */
	public ResponseEntity addLoseform(LoseformEntity LoseformEntity) {
			ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
			  	 int i =  LoseformDmlService.addLoseform(LoseformEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformBizService#updateLoseform(LoseformEntity LoseformEntity)
	 * @param LoseformEntity LoseformEntity
	 * @return ResponseEntity
	 */
	public ResponseEntity updateLoseform(LoseformEntity LoseformEntity) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = LoseformDmlService.updateLoseform(LoseformEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformBizService#queryAllLoseform(LoseformEntity LoseformEntity)
	 * @param LoseformEntity LoseformEntity
	 * @return String
	 */
	public String queryAllLoseform(LoseformEntity LoseformEntity) {
		List<LoseformEntity> list = LoseformQueryService.queryAllLoseform(LoseformEntity);
		convertCodeToName(list);
		return JSON.toJSONString(list);
	} 
	
	private void convertCodeToName(List<LoseformEntity> list){
		if(!CollectionUtils.isEmpty(list)){
			for(LoseformEntity e: list){
				e.setType(DictionaryUtil.conversionKeyToValue("76", e.getType()));
				e.setStatus(DictionaryUtil.conversionKeyToValue("78", e.getStatus()));
			}
		}
		
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformBizService#queryAllLoseform(LoseformEntity LoseformEntity)
	 * @param LoseformEntity LoseformEntity
	 * @return PageResult
	 */
	public String queryListForPageLoseform(LoseformEntity LoseformEntity) {
		List<LoseformEntity> list = LoseformQueryService.queryListForPageLoseform(LoseformEntity);
		convertCodeToName(list);
		return new PageResult( list, LoseformQueryService.queryCountLoseform(LoseformEntity)).toString();
	} 
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformQueryService#queryById(LoseformEntity LoseformEntity)
	 * @param BigInteger id
	 * @return
	 */
	public LoseformEntity queryById(BigInteger id) {
		return LoseformQueryService.queryById(id);
	}
	
	public void exportLoseform(LoseformEntity LoseformEntity, HttpServletResponse response) {
		List<LoseformEntity> exportList = null;
		String ids = LoseformEntity.getIds();
		if (ValidationUtil.isNullOrEmptyString(ids)) {
			exportList =LoseformQueryService.queryAllLoseform(LoseformEntity);
		} else {
			String[] idArray = ids.split(",");
			List<BigInteger> idList = new ArrayList<BigInteger>();
			for(String id : idArray) {
				idList.add(new BigInteger(id));
			}
			exportList = LoseformQueryService.queryByIds(idList);
			// 将字典中的code转换为name
		   //convertCodeToName(exportList);
		
		}
		convertCodeToName(exportList);
		ExcelExport.exportExcel(exportList, "LoseformEntityExcel", "LoseformEntity信息", response);
	}
	
	/** 
	 * 批量删除 数据处理
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.loseform.LoseformQueryService#queryById(LoseformEntity LoseformEntity)
	 * @param BigInteger id
	 * @return
	 */
	public ResponseEntity batchDelLoseform(LoseformEntity LoseformEntity) {
		String ids = LoseformEntity.getIds();
		String[] idArray = ids.split(",");
		List<LoseformEntity> LoseformEntityList = new ArrayList<LoseformEntity>();
		for(String id : idArray) {
			LoseformEntity LoseformModel = new LoseformEntity();
			LoseformModel.setId(new BigInteger(id));
			LoseformModel.setUpdateUser(UserContext.getUser().getName());
			LoseformModel.setUpdateTime(DateUtils.getCurrentTime());
			LoseformEntityList.add(LoseformModel);
		}
		return batchUpdateLoseform(LoseformEntityList);
	}
	
	/**
	 * 执行批量删除操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:40:31
	 * @param LoseformList
	 * @return
	 */
	public ResponseEntity batchUpdateLoseform(List<LoseformEntity> LoseformList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = LoseformDmlService.batchUpdateLoseform(LoseformList);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	
	/**
	 * 
	 * @author weiwei
	 * @date 2017年3月13日 上午10:24:53
	 * @see  com.jodinfo.outmirror.implementation.loseform.LoseformQueryService#queryById(LoseformEntity LoseformEntity)
	 * @param map
	 * @param excelimportcontext
	 * @param s
	 * @return
	 * @throws Exception
	 */
	/*public List<BigInteger> insertData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext, String s) throws Exception {
		String usrName = UserContext.getUser().getName();//数据创建人
		String creatTime = DateUtils.getCurrentTime();
		List<LoseformEntity> LoseformList = validateLoseformData(map, excelimportcontext,usrName,creatTime);
		if (!excelimportcontext.hasError() && LoseformList.size() > 0) {
			batchAddLoseform(LoseformList);
		}
		return null;
	}*/
	
	/**
	 * 
	 * TODO 验证数据 处理业务数据
	 * @author weiwei
	 * @date 2017年3月13日 上午9:33:30
	 * @see  com.jodinfo.outmirror.implementation.loseform.LoseformQueryService#queryById(LoseformEntity LoseformEntity)
	 * @param LoseformList
	 * @return
	 */
	/*public List<LoseformEntity> validateLoseformData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext,String usrName,String creatTime) {
		ExcelImportContext.DataError errorMsg = null;
		List<LoseformEntity> LoseformList = new ArrayList<LoseformEntity>();
		for (Map.Entry<Integer, List<Object>> entity : map.entrySet()) {
			List<Object> excelModelList = entity.getValue();
			if (ValidationUtil.isNullOrEmptyCollection(excelModelList)) {
		//		errorMsg = excelimportcontext.new DataError(InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET,
		//				"导入数据为空！",InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
		//		excelimportcontext.push(errorMsg);
			}else{
				//TODO 验证对应数据
				for (int i =0;i<excelModelList.size();i++) {
					LoseformEntity LoseformModel = (LoseformEntity) excelModelList.get(i);
	 				if (checkDataByEntityModel(shShopModel, excelimportcontext, i)) {
						break;
					}
					//TODO 实体对象加入对应参数值 
					LoseformModel = setEntityData(LoseformModel,usrName, creatTime);
					LoseformList.add(LoseformModel);
				}
			}
		}
		return LoseformList;
	}*/
	
	/**
	 * 
	 * 单个导入实体数据校验 有错误返回true
	 * @author weiwei
	 * @date 2017年3月28日 下午3:59:17
	 * @param eqEquipmentModel
	 * @param excelimportcontext
	 * @param i
	 * @return
	 */
	/*public boolean checkDataByEntityModel(LoseformEntity LoseformModel,ExcelImportContext excelimportcontext,int i) {
		if (checkSingleData(excelimportcontext, LoseformModel.getIsDel, i+2,"错误信息") 
			//	|| checkSingleData(excelimportcontext, LoseformModel.getEquipmentColor(), i+2, "颜色为空！")
			//	||checkSingleData(excelimportcontext, LoseformModel.getEquipmentModel(), i+2, "型号为空！")
				) {
			return true;
		}else{
			return false;
		}
	}*/
	
	/**
	 * 
	 * 设置报错信息
	 * @author weiwei
	 * @date 2017年3月22日 下午5:17:37
	 * @param excelimportcontext
	 * @param rowNumId
	 * @param errorMessage
	 * @param sheetNumId 现在只有一个sheet 就不传值 默认值即可
	 */
	/*public boolean checkSingleData(ExcelImportContext excelimportcontext,String checkVal,int rowNumId,String errorMessage) {
		boolean flag = false;
		ExcelImportContext.DataError errorMsg = null;
		if (ValidationUtil.isNullOrEmptyString(checkVal)) {
			errorMsg = excelimportcontext.new DataError(rowNumId,errorMessage,InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
			excelimportcontext.push(errorMsg);
			flag = true;
		}
		return flag;
	}*/
	
	/**
	 * 
	 * 导入单个实体添加统一导入人及导入时间
	 * @author zhuxiaoliu
	 * @date 2017年3月28日 下午4:05:15
	 * @param eqEquipmentModel
	 * @param usrName
	 * @param creatTime
	 * @return
	 */
	/*public LoseformEntity setEntityData(LoseformEntity LoseformModel,String usrName,String creatTime) {
		
		//LoseformModel.setEquipmentId(InventoryConstantUtil.EQ_EQUIPMENT_SEQUENCE);
		LoseformModel.setCreateTime(creatTime);
		LoseformModel.setCreateUsrName(usrName);
		LoseformModel.setLastUpdateUsrName(usrName);
		LoseformModel.setLastUpdateTime(creatTime);
		LoseformModel.setIsDel(SysConstant.IS_DEL_N);
		return LoseformModel;
	}*/
	
	
	/**
	 * 
	 * 执行批插入操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:37:14
	 * @param {moduleName}List
	 * @return
	 */
	public ResponseEntity batchAddLoseform(List<LoseformEntity> LoseformList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
		try{
			int i = LoseformDmlService.batchAddLoseform(LoseformList);
			 rs.setMessage(i+"条记录插入操作成功");
		 }catch(AbstractGenericException e){
			logger.error(e.getFullMessage());
			rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
		}catch(Exception e){
			String errorMessage = StringUtils.toString(e);
			logger.error(errorMessage);
			rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
		}
		return rs;
	}
	public List<BigInteger> insertData(Map<Integer, List<Object>> dataMap,
			ExcelImportContext context, String importType) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * 
	 * 
	 * @author cao.weiwei
	 * @date 2017年7月11日 下午5:59:23
	 * @see com.jodinfo.outmirror.api.loseform.service.LoseformBizService#updateLoseformAndBarcode(com.jodinfo.outmirror.api.loseform.entity.LoseformEntity)
	 * @param loseformEntity
	 * @return
	 */
	public ResponseEntity updateLoseformAndBarcode(
			LoseformEntity loseformEntity) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		loseformEntity.setUpdateTime(DateUtils.getCurrentTime());
		loseformEntity.setUpdateUser(loseformEntity.getCurrentUser().getName());
		List<LoseformBarcodeEntity> list = loseformEntity.getBarcodeList();
		IPlatformUser user = (IPlatformUser) loseformEntity.getCurrentUser();
		if(!CollectionUtils.isEmpty(list)){
			for(LoseformBarcodeEntity entity:list ){
				entity.setUpdateTime(DateUtils.getCurrentTime());
				entity.setUpdateUser(user.getName());
				entity.setUpdateUserId(user.getUserNo());
			}
		}
		LoseformTransactionService.updateLoseformAndBarcode(loseformEntity);
		return rs;
	}
	/**
	 * 
	 * 
	 * @author cao.weiwei
	 * @date 2017年7月11日 下午5:59:40
	 * @see com.jodinfo.outmirror.api.loseform.service.LoseformBizService#addLoseformAndBarcode(com.jodinfo.outmirror.api.loseform.entity.LoseformEntity)
	 * @param loseformEntity
	 * @return
	 */
	public ResponseEntity addLoseformAndBarcode(LoseformEntity loseformEntity) {
		checkIsExist(loseformEntity);
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		loseformEntity.setCreateTime(DateUtils.getCurrentTime());
		loseformEntity.setCreateUser(loseformEntity.getCurrentUser().getName());
		loseformEntity.setStatus("1");
		List<LoseformBarcodeEntity> list = loseformEntity.getBarcodeList();
		IPlatformUser user = (IPlatformUser) loseformEntity.getCurrentUser();
		if(!CollectionUtils.isEmpty(list)){
			for(LoseformBarcodeEntity entity:list ){
				entity.setCreateTime(DateUtils.getCurrentTime());
				entity.setCreateUser(user.getName());
				entity.setCreateUserId(user.getUserNo());
			}
		}
		LoseformTransactionService.addLoseformAndBarcode(loseformEntity); 
		return rs;
	}
	private void checkIsExist(LoseformEntity loseformEntity) {
		LoseformEntity loseformPam = new LoseformEntity();
		loseformPam.setWoNo(loseformEntity.getWoNo());
		LoseformEntity entity = LoseformQueryService.queryByEntity(loseformPam);
		if(entity!=null) throw new BusinessException("0","不能重复添加丢失单");
	}
	/**
	 * 
	 * 
	 * @author cao.weiwei
	 * @date 2017年7月12日 上午9:33:59
	 * @see com.jodinfo.outmirror.api.loseform.service.LoseformBizService#submitLoseForm(com.jodinfo.outmirror.api.loseform.entity.LoseformEntity)
	 * @param loseformEntity
	 * @return
	 */
	public ResponseEntity submitLoseForm(LoseformEntity loseformEntity) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		LoseformEntity form = checkFormIsExists(loseformEntity);
		form.setCurrentUser(loseformEntity.getCurrentUser());
		form.setCurrentUserString(loseformEntity.getCurrentUserString());
		if(Integer.parseInt(form.getStatus()) > 1 )throw new BusinessException("0","单据已提交,不能重复提交");
		setFormEquipmentList(form);
		setFormPurBarcode(form);
		LoseformTransactionService.sendMessageToOA(form);
		int i = updateLoseformStatus(loseformEntity, form);
		rs.setMessage(i+"条记录操作成功");
		return rs;
	}
	/**
	 * 查询设备列表
	 * @author cao.weiwei
	 * @date 2017年7月18日 下午2:01:42
	 * @param form
	 */
	private void setFormEquipmentList(LoseformEntity form) {
		LoseformBarcodeEntity LoseformBarcodeEntity = new LoseformBarcodeEntity();
		LoseformBarcodeEntity.setWoNo(form.getWoNo());
		List<LoseformBarcodeEntity> list = loseformBarcodeQueryService.queryAllLoseformBarcode(LoseformBarcodeEntity);
		form.setBarcodeList(list);
	}
	/**
	 * 查询单据的条码
	 * @author cao.weiwei
	 * @date 2017年7月18日 下午1:57:17
	 * @param form
	 */
	private void setFormPurBarcode(LoseformEntity form) {
		for(LoseformBarcodeEntity ce: form.getBarcodeList()){
			PurBarcodeEntity purcode = new PurBarcodeEntity();
			purcode.setBusinessKey(form.getWoNo());
			purcode.setStatusNumId("1");
			purcode.setEquipmentType(ce.getEqType());
			List<PurBarcodeEntity> list = purBarcodeQueryService.queryAllPurBarcode(purcode);
			transferUserNo2Account(list);
			ce.setPurBarcodeList(list);
		}
	}
	/**
	 * 将用户编号转成Account
	 * @author cao.weiwei
	 * @date 2017年8月31日 上午9:06:58
	 * @param list
	 */
	private void transferUserNo2Account(List<PurBarcodeEntity> list) {
		if(!CollectionUtils.isEmpty(list)){
			for(PurBarcodeEntity code: list){
				String userNo = code.getCreateUsrName();
				UserEntity userEntity = new UserEntity();
				userEntity.setUserNo(userNo);
				UserEntity user = userQueryService.queryByEntity(userEntity);
				if(user!=null) code.setCreateUsrName(user.getAccount());
			}
		}
	}
	/**
	 * 验证表单是否存在,不在则报错
	 * @author cao.weiwei
	 * @date 2017年7月18日 下午1:56:13
	 * @param loseformEntity
	 * @return
	 */
	private LoseformEntity checkFormIsExists(LoseformEntity loseformEntity) {
		LoseformEntity pamLoseformEntity = new LoseformEntity();
		pamLoseformEntity.setWoNo(loseformEntity.getWoNo());
		LoseformEntity form = LoseformQueryService.queryByEntity(pamLoseformEntity);  
		if(form==null )throw new BusinessException("0","未查到单据");
		return form;
	}
	
	/**
	 * 修改丢失单状态为已提交
	 * @author cao.weiwei
	 * @date 2017年7月18日 下午1:54:42
	 * @param loseformEntity
	 * @param form
	 * @return
	 */
	private int updateLoseformStatus(LoseformEntity loseformEntity, LoseformEntity form) {
		LoseformEntity updateEntity = new LoseformEntity();
		updateEntity.setStatus("2");
		updateEntity.setUpdateTime(DateUtils.getCurrentTime());
		updateEntity.setUpdateUser(((IPlatformUser)loseformEntity.getCurrentUser()).getName());
		updateEntity.setUpdateUserId(((IPlatformUser)loseformEntity.getCurrentUser()).getUserNo());
		updateEntity.setId(form.getId());
		int i = LoseformDmlService.updateLoseform(updateEntity);
		return i;
	}
	
	
}

